<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <!-- 列表视图 -->
    <view v-if="!showForm">
      <view class="flex justify-between items-center mb-[32rpx]">
        <text class="text-[48rpx] font-extrabold text-blue-600">紧急联系人</text>
        <nut-button type="primary" size="small" @click="showAddForm">新增联系人</nut-button>
      </view>

      <!-- 联系人列表 -->
      <view v-if="contactList.length > 0" class="space-y-[24rpx]">
        <view 
          v-for="contact in contactList" 
          :key="contact.id" 
          class="bg-white rounded-[16rpx] p-[32rpx] shadow-sm border border-gray-100"
        >
          <view class="flex justify-between items-start mb-[16rpx]">
            <view class="flex items-center">
              <text class="text-[36rpx] font-bold text-gray-900">{{ contact.name }}</text>
              <text class="ml-[16rpx] px-[12rpx] py-[4rpx] bg-blue-100 text-blue-600 text-[24rpx] rounded-[8rpx]">
                {{ contact.relation }}
              </text>
            </view>
            <view class="flex gap-[12rpx]">
              <nut-button type="default" size="small" @click="editContact(contact)">编辑</nut-button>
              <nut-button type="danger" size="small" @click="deleteContact(contact.id)">删除</nut-button>
            </view>
          </view>
          
          <view class="space-y-[8rpx] text-[28rpx] text-gray-600">
            <view class="flex items-center">
              <text class="w-[120rpx]">电话：</text>
              <text>{{ contact.phone }}</text>
            </view>
            <view class="flex items-center">
              <text class="w-[120rpx]">身份证：</text>
              <text>{{ contact.idcard }}</text>
            </view>
            <view v-if="contact.address" class="flex items-start">
              <text class="w-[120rpx]">地址：</text>
              <text class="flex-1">{{ contact.address }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="text-center py-[120rpx]">
        <view class="text-[120rpx] text-gray-300 mb-[32rpx]">📞</view>
        <text class="text-[32rpx] text-gray-500 mb-[16rpx] block">暂无紧急联系人</text>
        <text class="text-[28rpx] text-gray-400">点击上方按钮添加紧急联系人</text>
      </view>
    </view>

    <!-- 表单视图 - 使用现有的FormView组件 -->
    <view v-else>
      <view class="flex justify-between items-center mb-[32rpx]">
        <text class="text-[32rpx] font-bold">{{ isEdit ? "编辑联系人" : "新增联系人" }}</text>
        <nut-button type="default" size="small" @click="cancelForm">返回列表</nut-button>
      </view>

      <FormView 
        :fieldConfig="fieldConfig" 
        :form="form" 
        :showButtons="true" 
        @submit="submitForm" 
      />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { emergencyContactFields as fieldConfig } from './fields'
import FormView from '@/components/FormView.vue'
import { request } from '@/service/request'

// 状态管理
const showForm = ref(false)
const isEdit = ref(false)
const contactList = ref<any[]>([])
const form = reactive<any>({})
const currentEditId = ref<string>('')

// 页面加载
onMounted(async () => {
  await loadContactList()
})

// 加载联系人列表
async function loadContactList() {
  try {
    const result = await request.get<any>('/emergency/emergencyContact/list', {}, {
      useErrMsg: true
    })
    
    if (result && Array.isArray(result)) {
      contactList.value = result
    }
  } catch (error) {
    // 加载联系人列表失败
    Taro.showToast({ title: '加载失败', icon: 'error' })
  }
}

// 显示新增表单
function showAddForm() {
  isEdit.value = false
  showForm.value = true
  // 重置表单
  Object.keys(fieldConfig).forEach(key => {
    form[key] = ''
  })
}

// 编辑联系人
function editContact(contact: any) {
  isEdit.value = true
  currentEditId.value = contact.id
  showForm.value = true
  
  // 填充表单数据
  Object.keys(fieldConfig).forEach(key => {
    form[key] = contact[key] || ''
  })
}

// 取消表单
function cancelForm() {
  showForm.value = false
  isEdit.value = false
  currentEditId.value = ''
  // 重置表单
  Object.keys(fieldConfig).forEach(key => {
    form[key] = ''
  })
}

// 提交表单
async function submitForm(formData: any, fieldConfig: any) {
  try {
    // 表单验证
    if (!formData.name) {
      Taro.showToast({ title: '请输入姓名', icon: 'error' })
      return
    }
    if (!formData.phone) {
      Taro.showToast({ title: '请输入手机号', icon: 'error' })
      return
    }
    if (!formData.relation) {
      Taro.showToast({ title: '请选择关系', icon: 'error' })
      return
    }

    let result
    if (isEdit.value) {
      // 更新
      const params = {
        ...formData,
        id: currentEditId.value
      }
      result = await request.put<any>('/emergency/emergencyContact/update', params, {
        useErrMsg: true
      })
    } else {
      // 新增
      const params = {
        ...formData,
        userId: 'current_user_id' // 这里应该从用户状态获取
      }
      result = await request.post<any>('/emergency/emergencyContact/add', params, {
        useErrMsg: true
      })
    }

    if (result) {
      Taro.showToast({ 
        title: isEdit.value ? '更新成功' : '添加成功', 
        icon: 'success' 
      })
      
      // 重新加载列表
      await loadContactList()
      
      // 返回列表视图
      cancelForm()
    }
  } catch (error) {
    // 保存失败
    Taro.showToast({ title: '保存失败', icon: 'error' })
  }
}

// 删除联系人
async function deleteContact(id: string) {
  try {
    const result = await Taro.showModal({
      title: '确认删除',
      content: '确定要删除这个紧急联系人吗？',
      confirmText: '删除',
      cancelText: '取消'
    })

    if (result.confirm) {
      const deleteResult = await request.delete<any>(`/emergency/emergencyContact/delete/${id}`, {}, {
        useErrMsg: true
      })

      if (deleteResult) {
        Taro.showToast({ title: '删除成功', icon: 'success' })
        await loadContactList()
      }
    }
  } catch (error) {
    // 删除失败
    Taro.showToast({ title: '删除失败', icon: 'error' })
  }
}
</script>
